package org.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.example.domain.UserDomain;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/api/v1/users")
@RefreshScope
public class UserController {


    @Value("${test.value}")
    private Integer testVlue;

    AtomicInteger count = new AtomicInteger(0);

    @Autowired
    private UserService userService;

    @GetMapping("/{uid}")
    @ResponseBody
    public UserDomain getUser(@PathVariable("uid") Integer uid){
        return userService.selectUserById(uid);
    }

    @PostMapping("/{uid}")
    @ResponseBody
    public Boolean insertUser(@PathVariable("uid") Integer uid, @RequestBody UserDomain userDomain){
        userService.insertUser(userDomain);
        return true;
    }

    @GetMapping("/testvalue")
    @ResponseBody
    @SentinelResource(value = "testVlue")
    public Integer getTestVlue(){
        System.out.println("testVlue:"+ count.incrementAndGet());
        Random random = new Random();
        Integer ii = random.nextInt(6);
        try {
            System.out.println("enter sleep" + ii);
            TimeUnit.SECONDS.sleep(ii);
            System.out.println("exit sleep");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return testVlue;
    }

    @GetMapping("/testvalue2")
    @ResponseBody
    @SentinelResource(value = "testValue2")
    public Integer getTestVlue2(){
        System.out.println("testVlue:"+ count.incrementAndGet());
        Random random = new Random();
        Integer ii = random.nextInt(6);


        return ii;
    }

/*    @GetMapping(value = "/testproto", produces = "application/x-protobuf")
    @ResponseBody
    public UserProto getUser(){
        UserProto builder = new UserProto();
        builder.setId(1);
        builder.setName("test");
        return builder;
    }*/

}
